<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background: palegoldenrod;
            position: absolute;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        var div = document.querySelector('div');
        document.onkeydown = function (e){
            console.log(e.keyCode)
            var code = e.keyCode;
            var wid = window.innerWidth
            var hgt = window.innerHeight
            switch(code){
                case 65 :
                    var left1 = div.offsetLeft - 10
                    if(left1<0){
                        left1 = 0
                    }
                    div.style.left = left1 + 'px'
                break
                case 68 :
                    var left1 = div.offsetLeft + 10
                    if(left1>wid-div.offsetWidth){
                        left1 = wid-div.offsetWidth
                    }
                    div.style.left = left1 + 'px'
                break
                case 87 :
                    var top = div.offsetTop - 10
                    if(top<0){
                        top = 0
                    }
                    div.style.top = top + 'px'
                break
                case 83 :
                    var top = div.offsetTop + 10
                    if(top>hgt-div.offsetWidth){
                        top = hgt-div.offsetWidth
                    }
                    div.style.top = top + 'px'
                break         
            }
        }
    </script>
</body>
</html>